package com.tuniu.agents.common.command;

import com.tuniu.agents.command.CommandConfig;
import com.tuniu.agents.command.CommandStorage;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * This class implements the CommandStorage interface using Redis for storage.
 */
public class RedisCommandStateStorage implements CommandStorage {

    public static final String REDIS_PREFIX = "CommandConfig:";

    private HashOperations<String, String, CommandConfig> hashOperations;

    public RedisCommandStateStorage(RedisTemplate<String, Map<String, Object>> redisTemplate) {
        this.hashOperations = redisTemplate.opsForHash();
    }

    @Override
    public void saveCommandConfig(String conversationId, CommandConfig config) {
        hashOperations.put(REDIS_PREFIX + conversationId, config.getId(), config);
    }

    @Override
    public void saveCommandConfigs(String conversationId, List<CommandConfig> configs) {
        hashOperations.putAll(REDIS_PREFIX + conversationId, configs.stream().collect(Collectors.toMap(CommandConfig::getId, config -> config)));
    }

    @Override
    public CommandConfig getCommandConfig(String conversationId, String id) {
        return hashOperations.get(REDIS_PREFIX + conversationId, id);
    }

    @Override
    public Map<String, CommandConfig> getAllCommandConfigs(String conversationId) {
        return hashOperations.entries(REDIS_PREFIX + conversationId);
    }

    @Override
    public void deleteCommandConfig(String conversationId, String id) {
        hashOperations.delete(REDIS_PREFIX + conversationId, id);

    }

    @Override
    public void updateCommandConfig(String conversationId, CommandConfig config) {
        if (hashOperations.hasKey(REDIS_PREFIX + conversationId, config.getId())) {
            hashOperations.put(REDIS_PREFIX + conversationId, config.getId(), config);
        }
    }

}
